package com.hdax.gulimall.ware.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hdax.common.to.MemberEntity;
import com.hdax.common.utils.R;
import com.hdax.gulimall.ware.feign.MemberFeignService;
import com.hdax.gulimall.ware.vo.FareVo;
import com.hdax.gulimall.ware.vo.MemberReceiveAddressEntity;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Member;
import java.math.BigDecimal;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hdax.common.utils.PageUtils;
import com.hdax.common.utils.Query;

import com.hdax.gulimall.ware.dao.WareInfoDao;
import com.hdax.gulimall.ware.entity.WareInfoEntity;
import com.hdax.gulimall.ware.service.WareInfoService;


@Service("wareInfoService")
public class WareInfoServiceImpl extends ServiceImpl<WareInfoDao, WareInfoEntity> implements WareInfoService {



    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private MemberFeignService memberFeignService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        String key= (String) params.get("key");
        QueryWrapper<WareInfoEntity> wareInfoEntityQueryWrapper = new QueryWrapper<>();
        if(!StringUtils.isEmpty(key)){
            wareInfoEntityQueryWrapper.and(item->{
                item.eq("id",key).or().like("name",key).or().like("address",key);
            });
        }

        IPage<WareInfoEntity> page = this.page(
                new Query<WareInfoEntity>().getPage(params),
                wareInfoEntityQueryWrapper
        );

        return new PageUtils(page);
    }

    /**
     * 计算运费信息
     * @return
     */
    @Override
    public FareVo getFare(Long id) throws JsonProcessingException {
        //根据地址的id远程查询地址
        R info = memberFeignService.info(id);
        FareVo fareVo=new FareVo();
        Object memberReceiveAddress =  info.get("memberReceiveAddress");
        MemberReceiveAddressEntity memberReceiveAddressEntity = objectMapper.readValue(objectMapper.writeValueAsString(memberReceiveAddress), MemberReceiveAddressEntity.class);
        String phone = memberReceiveAddressEntity.getPhone();
        /**
         * 设置运费信息
         */
        String substring = phone.substring(phone.length()-1, phone.length());
        fareVo.setFare(new BigDecimal(substring));
        fareVo.setAddress(memberReceiveAddressEntity);
        return fareVo;
    }

}